package org.example.word;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.io.InputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Word文档解析抽象基类
 * @param <T> 解析结果类型
 */
@Slf4j
public abstract class AbstractWordDocumentParser<T> implements WordDocumentParser<T> {
    
    /**
     * 获取字段映射关系
     * @return 字段映射Map，key为文档中的字段名，value为对象属性名
     */
    protected abstract Map<String, String> getFieldMapping();
    
    /**
     * 获取结果类型
     * @return 结果类型Class
     */
    protected abstract Class<T> getResultType();
    
    /**
     * 处理特殊字段
     * @param document Word文档对象
     * @param result 解析结果对象
     */
    protected void processSpecialFields(XWPFDocument document, T result) {
        // 默认实现为空，子类可以覆盖此方法处理特殊字段
    }
    
    @Override
    public T parse(InputStream inputStream) throws Exception {
        // 创建输入流的副本
        byte[] bytes = inputStream.readAllBytes();
        
        // 解析基本字段
        T result = parseBasicFields(new java.io.ByteArrayInputStream(bytes));
        
        // 处理特殊字段
        try (XWPFDocument document = new XWPFDocument(new java.io.ByteArrayInputStream(bytes))) {
            processSpecialFields(document, result);
        }
        
        return result;
    }
    
    /**
     * 解析基本字段
     */
    private T parseBasicFields(InputStream inputStream) throws Exception {
        List<List<String>> rows = extractTables(inputStream);
        Map<String, String> labelValue = buildLabelValueMap(rows);
        T instance = getResultType().getDeclaredConstructor().newInstance();
        BeanWrapper wrapper = new BeanWrapperImpl(instance);
        
        for (Map.Entry<String, String> entry : getFieldMapping().entrySet()) {
            String label = entry.getKey();
            String fieldName = entry.getValue();
            String value = labelValue.get(label) != null ? labelValue.get(label) : labelValue.get("*"+ label);
            if (value != null) {
                wrapper.setPropertyValue(fieldName, value);
            }
        }
        
        return instance;
    }
    
    /**
     * 提取表格内容
     */
    private List<List<String>> extractTables(InputStream in) throws Exception {
        List<List<String>> rows = new ArrayList<>();
        try (XWPFDocument doc = new XWPFDocument(in)) {
            for (XWPFTable table : doc.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    List<String> cells = new ArrayList<>();
                    for (XWPFTableCell cell : row.getTableCells()) {
                        cells.add(cell.getText().trim());
                    }
                    rows.add(cells);
                }
            }
        }
        return rows;
    }
    
    /**
     * 构建标签值映射
     */
    private Map<String, String> buildLabelValueMap(List<List<String>> rows) {
        Map<String, String> map = new HashMap<>();
        for (List<String> row : rows) {
            for (int i = 0; i < row.size() - 1; i += 2) {
                String key = row.get(i);
                String value = row.get(i + 1);
                map.put(key, mapCheckbox(value));
            }
        }
        return map;
    }
    
    /**
     * 处理复选框
     */
    private String mapCheckbox(String text) {
        if (text.contains("□") || text.contains("☑")) {
            StringBuilder sb = new StringBuilder();
            Pattern pattern = Pattern.compile("☑(\\S+)");
            Matcher matcher = pattern.matcher(text);
            while (matcher.find()) {
                if (!sb.isEmpty()) {
                    sb.append(",");
                }
                sb.append(matcher.group(1));
            }
            return sb.toString();
        }
        return text;
    }
} 